package com.xy.bizportdemo.messagelist;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.messageutil.iface.ISmartSmsHolder;
import com.xy.bizportdemo.R;
import com.xy.bizportdemo.controller.SmartSMSManager;
import com.xy.bizportdemo.database.SmsDBManager;
import com.xy.bizportdemo.engine.BaseEngine;
import com.xy.bizportdemo.engine.MessageLoadEngine;
import com.xy.bizportdemo.util.SettingStateUtil;
import com.xy.smartsms.widget.ListViewScrollHelper;

import java.lang.ref.WeakReference;

/**
 * 企业信息详细列表的界面
 * Created by XIAOYUAN on 2016/11/24.
 */
public class MessageListActivity extends FragmentActivity implements ISmartSmsHolder, View.OnLayoutChangeListener {
    private static final String TAG = "MessageListActivity";

    private ListView mMessageList = null;
    private MessageListAdapter mListAdapter = null;

    private Handler mHandler = null;
    private Cursor mCursor = null;

    private String mPhoneNum = "";
    private String mName = "";

    private ListViewScrollHelper mListViewScrollHelper = null;
    private Context mContext;
    private EditText mTextEditor;
    private String mMessageSend;
    private InputMethodManager mInputMethodManger;

    //阀值设置为屏幕高度的1/3
    private int mKeyHeight;
    private SmsDBManager mSmsDBManager = null;
    private String mMsgId = null;
    private int mIndex = -1;

    private View mButtonToXYMenu = null;
    private LinearLayout mToolbar;
    private TextView mTvSubTitle;
    private TextView mTvTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_messagelist);
        initIntent();
        initVariables();
        initView();

//        SmartSmsCacheHelper.getInstance().parseBubble(mPhoneNum, 50);
//        SmartSmsCacheHelper.getInstance().loadBubble(mPhoneNum);
        //SmsProcessFacade.getInstance().backgroundParse(mPhoneNum, 50);
    }

    private void initIntent() {
        Intent intent = getIntent();
        mPhoneNum = intent.getStringExtra("phonenum");
        mName = intent.getStringExtra("name");
        mMsgId = intent.getStringExtra("msgId");
    }

    private void initView() {
        initTitle();
        initListView();
        initSendView();
        initComposeViewHolder();
    }

    private void initComposeViewHolder() {
        SmartSMSManager.getInstance().loadMenuProcessor().setupMenu(this, this, mPhoneNum);
//        SmartSmsMenuOptions options = new SmartSmsMenuOptions.Builder()
//                .setStubId(R.id.duoqu_menu_layout_stub)
//                .setChangeId(R.id.duoqu_button_menu)
//                .setEditId(R.id.bottom_panel)
//                .setHandler(mHandler)
//                .build();
//        mMenuHelper = new SmartSmsMenuHelper(this, mPhoneNum, options);

//        mComposeViewHolder = new ComposeViewHolder(this, mPhoneNum);
//        Map<String, String> map = new HashMap<String, String>();
//        map.put(ComposeViewHolder.ID_STUB, String.valueOf(R.id.duoqu_menu_layout_stub));
//        map.put(ComposeViewHolder.ID_CHANGE, String.valueOf(R.id.duoqu_button_menu));
//        map.put(ComposeViewHolder.ID_EDIT, String.valueOf(R.id.bottom_panel));
//        mComposeViewHolder.setMap(map);
    }


    private void initTitle() {
        mToolbar = (LinearLayout) findViewById(R.id.ll_back);
        mTvSubTitle = (TextView) findViewById(R.id.tv_title_sub);
        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mToolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        if (mName != null && mPhoneNum != null && !mPhoneNum.equalsIgnoreCase(mName) && !mPhoneNum.contains(mName)
                && !mName.contains(mPhoneNum)) {
            mTvTitle.setText(mName);
            mTvSubTitle.setText(mPhoneNum);
            mTvSubTitle.setVisibility(View.VISIBLE);
        } else {
            mTvTitle.setText(mName);
            mTvSubTitle.setText(mPhoneNum);
            mTvSubTitle.setVisibility(View.GONE);
        }

        //TODO huiney
        mButtonToXYMenu = findViewById(R.id.duoqu_button_menu);

        if (!SettingStateUtil.XY_MENU_MODE) {
            mButtonToXYMenu.setClickable(false);
            mButtonToXYMenu.setBackgroundResource(R.drawable.duoqu_btn_menu_disable);
        }
    }

    private void initVariables() {
        mKeyHeight = getWindowManager().getDefaultDisplay().getHeight() / 3;
        mInputMethodManger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mSmsDBManager = SmsDBManager.getInstance(getApplicationContext());

        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                Log.i(TAG, "handleMessage: ");
                boolean result = true;
                int what = message.what;
                switch (what) {
                    case MESSAGE_COMPLETE_ITEM:
                        ensureCompleteItem((View) message.obj);
                        break;

                    default:
                        result = false;
                        break;
                }

                return result;
            }
        });
    }

    private void sendMessage() {
        if (TextUtils.isEmpty(mMessageSend)) {
            return;
        }

        mSmsDBManager.writeSmsToSentBox(mPhoneNum, mMessageSend);
        mTextEditor.setText("");
    }

    private final TextWatcher mTextEditorWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // This is a workaround for bug 1609057.  Since onUserInteraction() is
            // not called when the user touches the soft keyboard, we pretend it was
            // called when textfields changes.  This should be removed when the bug
            // is fixed.
            onUserInteraction();
            mMessageSend = s.toString();
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    private void toggleSoftInput(boolean on) {
        if (on) {
            mInputMethodManger.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        } else if (mTextEditor != null) {
            mInputMethodManger.hideSoftInputFromWindow(mTextEditor.getWindowToken(), 0);
        }
    }

    private void initSendView() {
        mTextEditor = (EditText) findViewById(R.id.embedded_text_editor);
        mTextEditor.addTextChangedListener(mTextEditorWatcher);
        mTextEditor.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (KeyEvent.KEYCODE_ENTER == keyCode && event.getAction() == KeyEvent.ACTION_DOWN) {
                    sendMessage();

                    return true;
                }

                return false;
            }
        });

        findViewById(R.id.send_button_sms).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    sendMessage();
                }

                return true;
            }
        });
    }

    private void requestFocus() {
        mTextEditor.setFocusable(true);
        mTextEditor.setFocusableInTouchMode(true);
        mTextEditor.requestFocus();
        mTextEditor.findFocus();
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestFocus();
    }

    private void initListView() {
        mMessageList = (ListView) findViewById(R.id.message_list);
        mListAdapter = new MessageListAdapter(MessageListActivity.this, mCursor, R.layout.message_list_item2, mHandler);
        mMessageList.setAdapter(mListAdapter);
        mListViewScrollHelper = new ListViewScrollHelper(new WeakReference<ListView>(mMessageList));
        mMessageList.setOnScrollListener(mListViewScrollHelper);
        mMessageList.setScrollbarFadingEnabled(true);
        mMessageList.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    toggleSoftInput(false);
                }

                return false;
            }
        });

        new MessageLoadEngine(this).startReadSms(mPhoneNum, new BaseEngine.SmsReadListener() {
            @Override
            public void onSmsReadFinished(Cursor cursor) {
                mCursor = cursor;
                if (mMsgId != null && !"".equalsIgnoreCase(mMsgId) && mCursor != null && mCursor.moveToFirst()) {
                    do {
                        String cursor_MsgId = cursor.getString(cursor.getColumnIndex("_id"));
                        if (mMsgId.equalsIgnoreCase(cursor_MsgId)) {
                            mIndex = mCursor.getPosition();
                            break;
                        }
                    } while (mCursor.moveToNext());
                }

                setListSelection(mIndex);

                mHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        mListAdapter.changeCursor(mCursor);
                    }
                });
            }

            @Override
            public void onSmsReadError(String errorMsg) {
                Log.i(TAG, "onSmsReadError: " + errorMsg);
            }
        });

        mMessageList.addOnLayoutChangeListener(this);
    }

    private void setListSelection(final int position) {
        if (position == -1) {
            return;
        }

        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mMessageList.setSelection(position);
            }
        });
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        //old是改变前的左上右下坐标点值，没有old的是改变后的左上右下坐标点值
        //现在认为只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起
        if (oldBottom != 0 && bottom != 0 && ((oldBottom - bottom) > mKeyHeight)) {
            int listBottom = mMessageList.getAdapter().getCount() - 1;
            if (mMessageList.getFirstVisiblePosition() != listBottom) {
                setListSelection(listBottom);
            }
        }
    }

    @Override
    protected void onDestroy() {
        Log.i(TAG, "onDestroy: ");
//        if (mComposeViewHolder != null) {
//            mComposeViewHolder.destroy();
//            mComposeViewHolder = null;
//        }

//        SmartSmsCacheHelper.getInstance().clearBubble(mContext, mPhoneNum);
//        SmartSmsCacheHelper.getInstance().parseBubble(null, 200);
        //SmsProcessFacade.getInstance().backgroundParse(null, 200);

        if (mCursor != null) {
            mCursor.close();
        }

        super.onDestroy();
    }

    // ISmartSmsHolder start
    @Override
    public ViewGroup getParentView() {
        return mMessageList;
    }

    @Override
    public void ensureCompleteItem(View view) {
        mListViewScrollHelper.showCompleteItem(view);
    }

    @Override
    public boolean isScrolling() {
        return mListViewScrollHelper.isScrolling();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public int getMenuStubId() {
        return R.id.duoqu_menu_layout;
    }

    @Override
    public int getMenuEditId() {
        return R.id.bottom_panel;
    }

    @Override
    public int getMenuChangeId() {
        return R.id.duoqu_button_menu;
    }
}
